/*
* @Author: JINPENG
* @Date:   2018-07-18 20:35:42
* @Last Modified by:   JINPENG
* @Last Modified time: 2018-11-07 19:07:56
*/
'use strict'
require('./index.css');
require('page/common/nav/index.js');
require('page/common/header/index.js');
var _mm             = require('util/mm.js');
var _product        = require('service/product-service.js');
var _cart           = require('service/cart-service.js');
var templateIndex   = require('./index.string');
var page = {
	data : {
			productId : _mm.getUrlParam('productId') || '',
	},
	init : function(){
		this.onLond();
		this.bindEvent();
	},
	onLond    : function(){
		if (!this.data.productId) {
			_mm.goHome();
		}
		this.loadDetail();
	},
	bindEvent : function(){
		var _this = this;
		//切换主图
		$(document).on('mouseenter','.p-img-item',function(){
			var imageUrl = $(this).find('.p-img').attr('src');
			$('.main-img').attr('src',imageUrl);
		});
		//购买数量加减
		$(document).on('click','.p-count-btn',function(){
			var  type = $(this).hasClass('plus') ? 'plus' :'minus',
				 $pCount       	= $('.p-count'),
				 currCount 		= parseInt($pCount.val()),
				 minCount  		= 	1,
				 maxCount  		= _this.data.detailInfo.stock || 1;
				 if (type === 'plus') {
				 	$pCount.val(currCount < maxCount ? currCount + 1 : maxCount);
				 }
				 else if (type === 'minus') {
				 	$pCount.val(currCount > minCount ? currCount - 1 : minCount);
				 }
		});
		//加入购物车
		$(document).on('click','.cart-add',function(){
			_cart.addToCart({
				productId : _this.data.productId,
				count     : $('.p-count').val()
			},function(res){
				window.location.href = './result.html?type=cart-add';
			},function(errMsg){
				_mm.errorTips(errMsg);
			});
		});
	},
	//加载商品详情信息的数据
	loadDetail : function(){
		var _this 		= this,
			html 		= '',
			$pagewrap  	= $('.page-wrap');
			$pagewrap.html('<div class="loading"></div>');
		_product.getProductDetail(this.data.productId,function(res){
			_this.filter(res);
			//缓存接口数据
			_this.data.detailInfo = res;
			html = _mm.renderHtml(templateIndex,res);
			$pagewrap.html(html);
		},function(errMsg){
			$pagewrap.html('<p class="err-tip">此商品太稀缺，没有了</p>');
			});
	},
	filter : function(data){
		data.subImages = (data.subImages||"").split(',');
	}
};
$(function(){
	page.init();
})